﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxDataView;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxCallback;

namespace TireService.Website.Webshop
{
    public partial class Daek : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                TireServiceDB db = new TireServiceDB();

                // Get querystring input
                string TireType = Request.QueryString["daektype"];
                string Width = Request.QueryString["bredde"];
                string Height = Request.QueryString["hojde"];
                string Size = Request.QueryString["diameter"];

                txtHeight.Text = Height;
                txtWidth.Text = Width;
                txtSize.Text = Size;

                if (TireType != null & Width != null & Height != null & Size != null)
                {
                    if (TireType == "sommerdaek")
                    {
                        // Summertires
                        rbtnTireType.Items.FindByValue("2").Selected = true;
                    }
                    else
                    {
                        // Winter tires
                        rbtnTireType.Items.FindByValue("3").Selected = true;
                    }

                    //FillWidthDropDownList(db);
                    //ddlWidth.Items.FindByText(Width).Selected = true;

                    //FillHeightDropDownList(db, ddlWidth.SelectedItem.Text.ToString());
                    //ddlHeight.Items.FindByText(Height).Selected = true;

                    //FillSizeDropDownList(db, ddlWidth.SelectedItem.Text.ToString(), ddlHeight.SelectedItem.Text.ToString());
                    //ddlSize.Items.FindByText(Size).Selected = true;

                    // Show tires
                    //gvTires.DataSource = db.TireShopViews.Where(p => p.TireTypeId == Convert.ToInt32(rbtnTireType.SelectedItem.Value) & p.Width.ToString().Replace(".0", "") == Width & p.Height.ToString().Replace(".0", "") == Height & p.Size.ToString().Replace(".0", "") == Size).ToList();
                    //gvTires.DataSource = db.TireShopViews.Where(p => p.TireTypeId == Convert.ToInt32(rbtnTireType.SelectedItem.Value) & p.Width.ToString().Replace(".0", "") == Width & p.Height.ToString().Replace(".0", "") == Height & p.Size.ToString().Replace(".0", "") == Size).ToList();
                    gvTires.DataSource = db.TireShopViews.Where(p => p.TireTypeId == Convert.ToInt32(rbtnTireType.SelectedItem.Value) & p.Width == Convert.ToDecimal(Width) & p.Height == Convert.ToDecimal(Height) & p.Size == Convert.ToDecimal(Size)).ToList();
                    gvTires.DataBind();
                }
                else
                {
                    //// Load tire dimensions
                    //FillWidthDropDownList(db);
                    //ddlWidth.Items.FindByText("Bredde").Selected = true;

                    //FillHeightDropDownList(db, ddlWidth.SelectedItem.Text.ToString());
                    //ddlHeight.Items.FindByText("Højde").Selected = true;

                    //FillSizeDropDownList(db, ddlWidth.SelectedItem.Text.ToString(), ddlHeight.SelectedItem.Text.ToString());
                    //ddlSize.Items.FindByText("Diameter").Selected = true;

                    if (DateTime.Now <= Convert.ToDateTime("2013-08-01") & DateTime.Now >= Convert.ToDateTime("2013-03-01"))
                    {
                        // Summertires
                        rbtnTireType.Items.FindByValue("2").Selected = true;
                    }
                    else
                    {
                        // Winter tires
                        rbtnTireType.Items.FindByValue("3").Selected = true;
                    }
                }
            }
            
        }

        private void FillWidthDropDownList(TireServiceDB db) 
        {
            //List<string> width_list = new List<string>();

            //width_list.Add("Bredde");

            //foreach (string width in db.TireDimensionShopViews.Select(p => p.Width).Distinct().ToList())
            //{
            //    width_list.Add(width);
            //}
            
            //ddlWidth.DataSource = width_list;
            //ddlWidth.DataBind();
        }

        private void FillHeightDropDownList(TireServiceDB db, string Width) 
        {
            //List<string> height_list = new List<string>();

            //height_list.Add("Højde");

            //if (Width == "Bredde")
            //{
            //    ddlHeight.Items.Clear();
            //    FillSizeDropDownList(db, Width, "Højde");
            //}
            //else
            //{
            //    foreach (string height in db.TireDimensionShopViews.Where(p => p.Width == Width).Select(p => p.Height).Distinct().ToList())
            //    {
            //        height_list.Add(height);
            //    }
            //}

            //ddlHeight.DataSource = height_list;
            //ddlHeight.DataBind();
        }

        private void FillSizeDropDownList(TireServiceDB db, string Width, string Height) 
        {
            //List<string> size_list = new List<string>();

            //size_list.Add("Diameter");

            //if (Width == "Bredde" | Height == "Højde")
            //{
            //    ddlSize.Items.Clear();
            //}
            //else
            //{
            //    foreach (string size in db.TireDimensionShopViews.Where(p => p.Width == Width & p.Height == Height).Select(p => p.Size).Distinct().ToList())
            //    {
            //        size_list.Add(size);
            //    }
            //}

            //ddlSize.DataSource = size_list;
            //ddlSize.DataBind();
        }

        protected void ddlHeight_Callback(object source, CallbackEventArgsBase e)
        {
            TireServiceDB db = new TireServiceDB();

            FillHeightDropDownList(db, e.Parameter);
        }

        protected void ddlSize_Callback(object source, CallbackEventArgsBase e)
        {
            TireServiceDB db = new TireServiceDB();

            // Get input value (0: Width, 1: Height)
            string[] param = e.Parameter.Split('|');

            FillSizeDropDownList(db, param[0], param[1]);
        }

        protected void btnSearchTire_Click(object sender, EventArgs e)
        {
            //string TireType = "daektype=" + rbtnTireType.SelectedItem.Value.ToString().Replace("2", "sommerdaek").Replace("3", "vinterdaek");
            //string TireDimensions = "bredde=" + ddlWidth.SelectedItem.Value.ToString() + "&hojde=" + ddlHeight.SelectedItem.Value.ToString() + "&diameter=" + ddlSize.SelectedItem.Value.ToString();

            string TireType = "daektype=" + rbtnTireType.SelectedItem.Value.ToString().Replace("2", "sommerdaek").Replace("3", "vinterdaek");
            string TireDimensions = "bredde=" + txtWidth.Text + "&hojde=" + txtHeight.Text + "&diameter=" + txtSize.Text;

            Response.Redirect("Daek.aspx?" + TireType + "&" + TireDimensions);
        }

        public string DeterminTireType(object TireTypeId)
        {
            int tiretypeid = Convert.ToInt32(TireTypeId);

            string tiretype = "";

            if (tiretypeid == 2)
            {
                tiretype = "Sommerdæk";
            }

            if (tiretypeid == 3)
            {
                tiretype = "Vinterdæk";
            }

            return tiretype;
        }

        public string GetImagePath(string value)
        {
            string ImagePath = "";
            int interval = Convert.ToInt32(value);

            if (interval == 1)
            {
                ImagePath = "~/Images/Webshop/a.png";
            }
            if (interval == 2)
            {
                ImagePath = "~/Images/Webshop/b.png";
            }
            if (interval == 3)
            {
                ImagePath = "~/Images/Webshop/c.png";
            }
            if (interval == 4)
            {
                ImagePath = "~/Images/Webshop/e.png";
            }
            if (interval == 5)
            {
                ImagePath = "~/Images/Webshop/f.png";
            }
            if (interval == 6)
            {
                ImagePath = "~/Images/Webshop/g.png";
            }
            return ImagePath;
        }

        public string CalculateCostPrice(string CostPrice, string Size)
        {
            decimal costprice = Convert.ToDecimal(CostPrice);
            int size = Convert.ToInt32(Size.Replace(",0", ""));

            // Add db
            if (size <= 15)
            {
                costprice += 100;
            }

            if (size > 15 & size <= 17)
            {
                costprice += 125;
            }

            if (size > 17)
            {
                costprice += 150;
            }

            // Add vat to price
            costprice += costprice * Convert.ToDecimal("1,25");

            return string.Format("{0:N}", costprice);
        }

        /// <summary>
        /// Callback function that add selected product to purchase basket
        /// </summary>
        protected void callBackAddProduct_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                string[] param = e.Parameter.Split('|');

                int productid = Convert.ToInt32(param[0]);
                int quantity = Convert.ToInt32(param[1]);

                ShoppingCartActions cartActions = new ShoppingCartActions();

                cartActions.AddToCart(productid, quantity);
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        /// <summary>
        /// Callback function that add selected product to purchase basket
        /// </summary>
        protected void callBackAddProductAndCheckOut_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                string[] param = e.Parameter.Split('|');

                int productid = Convert.ToInt32(param[0]);
                int quantity = Convert.ToInt32(param[1]);

                ShoppingCartActions cartActions = new ShoppingCartActions();

                cartActions.AddToCart(productid, quantity);
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        

        protected void btnAddToCart_Init(object sender, EventArgs e)
        {
            ASPxButton btn = sender as ASPxButton;
            
            GridViewPreviewRowTemplateContainer container = btn.NamingContainer as GridViewPreviewRowTemplateContainer;
            //GridViewDataItemTemplateContainer container = btn.NamingContainer as GridViewDataItemTemplateContainer;
            btn.ClientSideEvents.Click = "function(s, e) { ShowAddProduct(" + container.KeyValue.ToString() + "); }";

            //DataBinder.Eval(container.DataItem, "TirePriceListId")
        }

    }

    public class CartItem
    {
        public string ItemId { get; set; }

        public string CartId { get; set; }

        public string Description { get; set; }

        public decimal UnitPrice { get; set; }

        public int Quantity { get; set; }

        public decimal TotalPrice { get; set; }

        public System.DateTime DateCreated { get; set; }

        public int ProductId { get; set; }
    }


    public class ShoppingCartActions
    {
        public string ShoppingCartId { get; set; }

        private TireServiceDB db = new TireServiceDB();

        public const string CartSessionKey = "CartId";

        public void RemoveFromCart(int id)
        {
            // Get shoppingcartid
            ShoppingCartId = GetCartId();

            // Retrieve the shoppingcart products from session
            List<CartItem> caritems = new List<CartItem>();
            if (HttpContext.Current.Session["ShoppingCart"] != null)
            {
                caritems = (List<CartItem>)HttpContext.Current.Session["ShoppingCart"];
            }

            if (caritems != null)
            {
                var cartItem = caritems.SingleOrDefault(c => c.CartId == ShoppingCartId & c.ProductId == id);

                // Remove existing cartitem
                caritems.Remove(cartItem);

                // Store shoppingcart in session again
                HttpContext.Current.Session["ShoppingCart"] = caritems;
            }
        }

        public void AddToCart(int id, int quantity)
        {
            // Get shoppingcartid
            ShoppingCartId = GetCartId();

            // Retrieve the shoppingcart products from session
            List<CartItem> caritems = new List<CartItem>();
            if (HttpContext.Current.Session["ShoppingCart"] != null)
            {
                caritems = (List<CartItem>)HttpContext.Current.Session["ShoppingCart"];
            }

            if (caritems != null)
            {
                var cartItem = caritems.SingleOrDefault(c => c.CartId == ShoppingCartId & c.ProductId == id);

                if (cartItem == null)
                {
                    // Create a new cart item if no cart item exists.                 
                    cartItem = new CartItem();
                    cartItem.ItemId = Guid.NewGuid().ToString();
                    cartItem.ProductId = id;
                    cartItem.CartId = ShoppingCartId;

                    if (id < 1000)
                    {
                        // HACK: NOT A GOOD SOLUTION BELOW - HARDCODED

                        // 0 and -1 (0: Private delivery, -1: Business delivery
                        // 1-17: Subscriptions

                        if (id == 0)
                        {
                            // Private delivery
                            cartItem.Description = "Levering privat";
                            cartItem.UnitPrice = 199;
                        }

                        if (id == -1)
                        {
                            // Business delivery
                            cartItem.Description = "Levering erhverv";
                            cartItem.UnitPrice = 99;
                        }

                        if (id > 0 & id < 8)
                        {
                            // Get subscription
                            Subscription subscription = db.GetSubscription(id);

                            // Subscription
                            cartItem.Description = subscription.Description;
                            cartItem.UnitPrice = subscription.StandardPrice;
                        }
                    }
                    else
                    {
                        // Tire product
                        TireShopView tire = db.TireShopViews.SingleOrDefault(p => p.TirePriceListId == id);

                        if (tire == null)
                        {
                            // Raise Error
                        }
                        else
                        {
                            // Calculate unitprice
                            decimal costprice = Convert.ToDecimal(tire.CostPrice);
                            int size = Convert.ToInt32(tire.Size.ToString().Replace(",0", ""));

                            // Add db
                            if (size <= 15)
                            {
                                costprice += 100;
                            }

                            if (size > 15 & size <= 17)
                            {
                                costprice += 125;
                            }

                            if (size > 17)
                            {
                                costprice += 150;
                            }

                            // Add vat to price
                            costprice += costprice * Convert.ToDecimal("1,25");

                            string unitprice = string.Format("{0:N}", costprice);

                            cartItem.UnitPrice = Convert.ToDecimal(unitprice);
                            cartItem.Description = tire.FullDescription;
                        }
                    }

                    cartItem.Quantity = quantity;
                    cartItem.TotalPrice = (cartItem.UnitPrice * cartItem.Quantity);
                    cartItem.DateCreated = DateTime.Now;

                    // Add item
                    caritems.Add(cartItem);
                }
                else
                {
                    CartItem newCartItem = new CartItem();
                    newCartItem = cartItem;

                    newCartItem.Quantity = newCartItem.Quantity + quantity;
                    newCartItem.TotalPrice = (newCartItem.Quantity * newCartItem.UnitPrice);

                    // Remove existing cartitem
                    caritems.Remove(cartItem);

                    // Add new/updated item
                    caritems.Add(newCartItem);
                }
            }
            else
            {
                // Create a new cart item if no cart item exists.                 
                CartItem cartItem = new CartItem();
                cartItem.ItemId = Guid.NewGuid().ToString();
                cartItem.ProductId = id;
                cartItem.CartId = ShoppingCartId;

                if (id < 1000)
                {
                    // None tire products
                    cartItem.Description = "";
                    cartItem.UnitPrice = 100;
                }
                else
                {
                    // Tire product
                    TireShopView tire = db.TireShopViews.SingleOrDefault(p => p.TirePriceListId == id);

                    if (tire == null)
                    {
                        // Raise Error
                    }
                    else
                    {
                        // Calculate unitprice
                        decimal costprice = Convert.ToDecimal(tire.CostPrice);
                        int size = Convert.ToInt32(tire.Size.ToString().Replace(",0", ""));

                        // Add db
                        if (size <= 15)
                        {
                            costprice += 100;
                        }

                        if (size > 15 & size <= 17)
                        {
                            costprice += 125;
                        }

                        if (size > 17)
                        {
                            costprice += 150;
                        }

                        // Add vat to price
                        costprice += costprice * Convert.ToDecimal("1,25");

                        string unitprice = string.Format("{0:N}", costprice);

                        cartItem.UnitPrice = Convert.ToDecimal(unitprice);
                        cartItem.Description = tire.FullDescription;
                    }
                }

                cartItem.Quantity = quantity;
                cartItem.TotalPrice = (cartItem.UnitPrice * cartItem.Quantity);
                cartItem.DateCreated = DateTime.Now;

                // Add item
                caritems.Add(cartItem);
            }          

            // Store shoppingcart in session again
            HttpContext.Current.Session["ShoppingCart"] = caritems;
        }

        public string GetCartId()
        {
            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
                {
                    HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class.     
                    Guid tempCartId = Guid.NewGuid();
                    HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return HttpContext.Current.Session[CartSessionKey].ToString();
        }

        public List<CartItem> GetCartItems()
        {
            ShoppingCartId = GetCartId();

            // Retrieve the shoppingcart products from session
            List<CartItem> caritems = (List<CartItem>)HttpContext.Current.Session["ShoppingCart"];

            return caritems.Where(c => c.CartId == ShoppingCartId).ToList();
        }
    }

}